<script setup lang='ts'>
import {ref, computed} from 'vue'
import type {Ref, ComputedRef} from 'vue'
import {useRouter} from 'vue-router'
import type {Router} from 'vue-router'
import {dosendmsgcode, docheckcode} from '../../api/user'
import { showToast,showDialog } from 'vant';
import { log } from 'console'
const telcode: Ref<string> = ref('')

const router: Router = useRouter()

// 找到手机号
  const tel = sessionStorage.getItem('tel')


// 判断下一步按钮能否被点击
const flag: ComputedRef<boolean> = computed(()=>{
  return telcode.value.length == 5
})


// 提交表单的事件
function onSubmit(){

  // 发送数据请求验证输入验证码是否正确
  docheckcode({
      tel,
      telcode: telcode.value
  }).then(res => {
    console.log(res);
    if(res.data.code == 200){
      // 可以下一步
      router.push('/register/step3')
    }else {
      showDialog({ message: res.data.message + '请重新输入！' });
    }
  })

  // 正确就进入下一页面
  // router.push('/register/step3')
}

// 按钮显示的内容
const text: Ref<string> = ref('发送验证码')

// 用来记录倒计时时间用的
const time: Ref<number> = ref(10)
// 发送验证码按钮的点击事件
let timer = null
function sendCodeFn(){
  // 点击的时候要先清除定时器
  clearInterval(timer)

  // 发送数据请求
  
  dosendmsgcode({
    tel
  }).then(res => {
    console.log(res.data);
    if(res.data.code == 200){
      // console.log(111111111,res.data.message + res.data.data);
      
      // showToast(res.data.message + res.data.data)
       showDialog({ message: res.data.message + res.data.data });
      
    }
  })

  timer = setInterval(()=>{
    time.value--
    text.value = time.value + 's 后获取'

    if(time.value == 0){
      clearInterval(timer)
      time.value = 10
      text.value = '重新获取'
    }

  }, 1000)
}

</script>
<template>
   

      <div class='content' style="padding-top: 30px;">
        <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-field
            v-model="telcode"
            name="验证码"
            label="验证码"
            placeholder="请输入验证码"
            :rules="[{ required: true, message: '请填写验证码' }]"
          >
            <template #button>
              <van-button :disabled='time < 10' @click="sendCodeFn" size='mini' >
                {{text}}
              </van-button>
            </template>
          </van-field>
        </van-cell-group>

        <div style="padding: 30px 20px 0 20px;">
          <van-button :disabled='!flag' native-type="submit" round block color='#f66' >
            下一步
          </van-button>
        </div>
        
      </van-form>

      </div>

</template>
<style scoped lang="scss">
    
</style>